package com.example.win.android_banduyujia.peopleactivity.activity.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.example.win.android_banduyujia.R;
import com.example.win.android_banduyujia.entity.Constants;
import com.example.win.android_banduyujia.http.request.CerRequest;
import com.example.win.android_banduyujia.http.response.BaseHttpResponse;
import com.example.win.android_banduyujia.lib.util.FileUtils;
import com.example.win.android_banduyujia.lib.util.StrUtils;
import com.example.win.android_banduyujia.login.application.LoginApplication;
import com.example.win.android_banduyujia.peopleactivity.activity.activity.openactivity.DataActivity.CerNameActivity;
import com.example.win.android_banduyujia.peopleactivity.ui.activity.BaseTitleBarActivity;
import com.example.win.android_banduyujia.ui.dialog.CustomListDialog;
import com.example.win.android_banduyujia.ui.popupWindow.Popupwindows;
import com.example.win.android_banduyujia.ui.view.ImageLoader;

import java.io.File;
import java.util.UUID;

/**
 * Created by huchun on 2015/8/15.
 */
public class CertActivity extends BaseTitleBarActivity implements View.OnClickListener {
     public static final String TAG = CertActivity.class.getSimpleName();

    private ImageView   mImagePic;
    private TextView  mTxtCerName, mTxtGrade, mTxtCerPhone,mTxtCerBoolName,mTxtOrgztion,mTxtTear,mTxtItemBook,mTxtGrade1,mTxtName1;

    private Popupwindows popupwindows;
    private String  mFinish = " ";
    private Intent picToView;

    private LoginApplication  mLoginInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_certfition_book);

        InitTitles();
        InitViews();
    }

    private void InitTitles() {
        setTitle(R.string.text_view_certification_certificate);
        showLeftBackButton();
        setRightButtonImageAndListener(R.mipmap.close, mRightListener);
       // setRightTextViewListener(R.string.text_view_submit_audit_finish, mRightListener);
    }

    private View.OnClickListener mRightListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(StrUtils.isEmpty(mFinish)){

            }
        }
    };

    private void Finish() {

    }

    private void InitViews() {
       /* mTxtCerName = (TextView)findViewById(R.id.submit_title_list_item_name);
        mTxtGrade = (TextView)findViewById(R.id.submit_title_list_item_grade);*/
        mImagePic = (ImageView) findViewById(R.id.layout_certfition_image_view);
        mTxtCerPhone = (TextView)findViewById(R.id.submit_title_list_item_phone);
        mTxtCerBoolName = (TextView)findViewById(R.id.submit_title_list_item_cer_name);
        mTxtOrgztion = (TextView)findViewById(R.id.submit_title_list_item_organization);
      //  mTxtTear = (TextView)findViewById(R.id.submit_title_list_item_tercher);
        mTxtItemBook = (TextView)findViewById(R.id.submit_title_list_item_book);
       // mTxtGrade1 = (TextView)findViewById(R.id.submit_title_list_item_name1);
        //mTxtName1 = (TextView)findViewById(R.id.submit_title_list_item_grade1);

        /*mTxtCerName.setOnClickListener(this);
        mTxtGrade.setOnClickListener(this);*/

        mTxtCerPhone.setOnClickListener(this);
        mTxtCerBoolName.setOnClickListener(this);
        mTxtOrgztion.setOnClickListener(this);
     //   mTxtTear.setOnClickListener(this);
        mTxtItemBook.setOnClickListener(this);
     //   mTxtGrade1.setOnClickListener(this);

        mImagePic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Popupwindows(CertActivity.this, mImagePic);
            }
        });
    }

    @Override
    public void onClick(View v) {
         switch (v.getId()){
             case  R.id.layout_certfition_image_view: // 上传证书图片
                 UpictureActivity();
                 break;
             case  R.id.submit_title_list_item_phone: // 上传证书文字
                 UpictureActivity();
                 break;
             case  R.id.submit_title_list_item_cer_name: // 证书名称
                  CernameActivity();
                 break;
             case  R.id.submit_title_list_item_organization: // 机构

                 break;
             case  R.id.submit_title_list_item_book: // 瑜伽培训小时数

                 break;
             /*case  R.id.submit_title_list_item_tercher: // 培训名师

                 break;
             case  R.id.submit_title_list_item_name1: // 课程名称

                 break;*/
         }
    }

    private void CernameActivity() {
        startActivity(new Intent(this, CerNameActivity.class));
    }

    private CustomListDialog  mListDialog;
    private static final int REQUEST_CODE_CAMERA = 0X000;
    private static final int REQUEST_CODE_ALBUM = 0X001;
    private  View  view;

    private void UpictureActivity() {
        /*Popupwindows  popupwindows = new Popupwindows(CertActivity.this);
        popupwindows.showAtLocation(mImagePic);*/
        String[]  array = getResources().getStringArray(R.array.choose_image_dialog);
        mListDialog = new CustomListDialog(this, R.string.personnal_info_activity_update_header, array);
        mListDialog.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position){
                    case 0:
                        startCameraCropActivity(REQUEST_CODE_ALBUM);
                        break;
                    case 1:
                        startPictureCropActivity(REQUEST_CODE_CAMERA);
                        break;
                 }
                   mListDialog.dismiss();
            }
        });
         mListDialog.show();
    }

    public class Popupwindows extends PopupWindow{

        public Popupwindows(Context mContext, View parent) {
            View view=View.inflate(mContext, R.layout.title_pic_item, null);
            view.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.fade_ins));
            LinearLayout  ll_poplayout = (LinearLayout) view.findViewById(R.id.ll_popup);
            ll_poplayout.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.push_bottom_in_2));

            setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
            setBackgroundDrawable(new BitmapDrawable());
            setFocusable(true);
            setOutsideTouchable(true);
            setContentView(view);
            showAtLocation(parent, Gravity.BOTTOM, 0, 0);
            update();

            Button bt1 = (Button) view.findViewById(R.id.item_popupwindows_camera);
            Button bt2 = (Button) view.findViewById(R.id.item_popupwindows_Photo);
            Button bt3 = (Button) view.findViewById(R.id.item_popupwindows_cancel);
            bt1.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    photo();
                    dismiss();
                }
            });
            bt2.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    picture();
                    dismiss();
                }
            });
            bt3.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    dismiss();
                }
            });
        }
        }

    private static final int TAKE_PICTURE = 0x000000;
    private static final int TAKE_PHOTO = 0x000001;
    private static final int TAKE_CROP = 0x000002;

    private void photo() {
        String status = Environment.getExternalStorageState();
        if(status.equals(Environment.MEDIA_MOUNTED)){
            File dir = new File(Environment.getExternalStorageDirectory() + "/image/");
            if(!dir.exists())
                dir.mkdirs();

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            // 下面这句指定调用相机拍照后的照片存储的路径
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), ".jpg")));
            intent.putExtra("return-data", true);
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
            startActivityForResult(intent, TAKE_PICTURE);
        }else{
            showToast("没有卡");
        }
    }

    private void picture() {
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, TAKE_PHOTO);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case TAKE_PHOTO: // 如果是直接从相册获取
                startPhotoZoom(data.getData());
                break;
            case TAKE_PICTURE:  // 如果是调用相机拍照时
                File temp = new File(Environment.getExternalStorageDirectory() + "/.jpg");
                startPhotoZoom(Uri.fromFile(temp));
                break;
            case TAKE_CROP:  // 取得裁剪后的图片
                if (data != null) {
                    setPicToView(data);
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    // 裁剪图片方法实现 173 * 174
    private void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");

        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, TAKE_CROP);
    }

    //	保存裁剪之后的图片数据 201 * 202
    public void setPicToView(Intent data) {
       Bundle exreas = data.getExtras();
       if(exreas != null){
           Bitmap  photo = exreas.getParcelable("data");
           Drawable drawable = new BitmapDrawable(photo);

           /* 下面注释的方法是将裁剪之后的图片以Base64Coder的字符方式上 传到服务器，
		       QQ头像上传采用的方法跟这个类似 213*/
           mImagePic.setImageBitmap(photo);
          // saveImage(data);
       }
    }

    private String  mImageName = " ";
    private void saveImage(Intent data) {
        if(FileUtils.exists(Constants.IMAGE_CAPTURE_URI.getPath())){
            String imageName = UUID.randomUUID().toString() + ".jpg";
            //file path 存文件的地址
            String path = Environment.getExternalStorageDirectory().toString() + Constants.PATH_USER_HEADER + imageName;
            FileUtils.fileCpy(Constants.IMAGE_CAPTURE_URI.getPath(), path, true);
            Bitmap bit = BitmapFactory.decodeFile(path);
            if(bit != null){
                mImageName = imageName;
                mImagePic.setImageDrawable(new BitmapDrawable(bit));
                ImageLoader.getInstance().putBitmapIntoMemCache(path, bit);

                CerRequest request = new CerRequest(LoginApplication.getInstance().getAccessToken());
                request.doRequestFile(CertActivity.this, BaseHttpResponse.class, true, mCallbackHandler,path);
            }else{
                showToast("上传失败");
            }
            FileUtils.clearFileInDir(Constants.IMAGE_CAPTURE_URI.getPath());
        }
    }

    private Handler mCallbackHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            Log.v("avatar", "yes");
        }
    };
}
